package com.coke.im.client.stream;

import com.coke.im.client.exception.MessageException;
import com.coke.im.client.type.ExecStatus;
import com.coke.im.client.type.MessageHeadConstant;
import com.coke.im.client.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

public class Message {

	private Map<String, String> heads = new HashMap<String, String>();

	public void setHead(String key, String value) {
		heads.put(key, value);
	}

	public String getType() {
		return heads.get(MessageHeadConstant.TYPE);
	}

	public int getLength() {
		String len = heads.get(MessageHeadConstant.LENGTH);
		if (StringUtils.isBlank(len)) {
			return -1;
		}
		return Integer.parseInt(len.trim());
	}

	public String getHead(String key) {
		return heads.get(key);
	}

	private byte[] body;

	public byte[] getBody() {
		return body;
	}

	public void setBody(byte[] body) {
		this.body = body;
	}

	public byte[] toBytes() throws Exception {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int num = (body == null ? 0 : body.length);
			this.setHead(MessageHeadConstant.LENGTH, String.valueOf(num));
			for (String key : heads.keySet()) {
				baos.write((key + ":" + heads.get(key) + "\r\n").getBytes());
			}
			baos.write("\r\n".getBytes());

			if (num > 0) {
				baos.write(body);
			}
			baos.write("-\r\n-".getBytes());
			return baos.toByteArray();
		} catch (Exception e) {
			throw new MessageException(ExecStatus.MESSAGE_FORMAT_ERROR);
		}

	}

}
